package io.api.modules.project.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.admin.common.exception.RenException;
import io.admin.common.service.impl.CrudServiceImpl;
import cn.hutool.core.util.StrUtil;
import io.api.modules.project.dao.FileUrlDao;
import io.api.modules.project.dto.FileUrlDTO;
import io.api.modules.project.entity.FileUrlEntity;
import io.api.modules.project.service.FileUrlService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * 文件地址管理表
 *
 * @author Mark sunlightcs@gmail.com
 * @since 1.0.0 2024-07-12
 */
@Service
public class FileUrlServiceImpl extends CrudServiceImpl<FileUrlDao, FileUrlEntity, FileUrlDTO> implements FileUrlService {

    @Value("${file.user.path}")
    private String ADDRESS_FILE;

    @Override
    public QueryWrapper<FileUrlEntity> getWrapper(Map<String, Object> params){
        String id = (String)params.get("id");

        QueryWrapper<FileUrlEntity> wrapper = new QueryWrapper<>();
        wrapper.eq(StrUtil.isNotBlank(id), "id", id);

        return wrapper;
    }

    @Override
    public FileUrlDTO get(Long id) {
        FileUrlDTO fileUrlDTO = super.get(id);
        if (fileUrlDTO == null){
            throw new RenException("找不到对应文件");
        }
        return fileUrlDTO;
    }

    @Override
    public List<FileUrlEntity> selectByKeysId(Long keysId) {
        return baseDao.selectList(new LambdaQueryWrapper<FileUrlEntity>().eq(FileUrlEntity::getKeysId, keysId));
    }

    @Override
    public void deleteByKeysId(Long keysId) {
        List<FileUrlEntity> list = selectByKeysId(keysId);
        for (FileUrlEntity entity : list) {
            FileSystemResource resource = new FileSystemResource(ADDRESS_FILE + entity.getUrl());
            if (resource.exists()) {
                resource.getFile().delete();
            }
        }
        baseDao.deleteByKeysId(keysId);
    }

    @Override
    public void deleteById(Long id) {
        delFile(id);
        super.deleteById(id);
    }

    @Override
    public void delete(Long[] ids) {
        if (ids.length > 0){
            for (Long id : ids) {
                delFile(id);
            }
            super.delete(ids);
        }
    }

    private void delFile(Long id) {
        FileUrlDTO data = this.get(id);
        FileSystemResource resource = new FileSystemResource(ADDRESS_FILE + data.getUrl());
        if (resource.exists()) {
            resource.getFile().delete();
        }
    }
}